//
//  GLPrebuiltLiveStreamingVC.swift
//  GLUZSwift
//
//  Created by yu on 2025/3/28.
//

import Foundation
import IQKeyboardManagerSwift
import JFPopup
import WebKit
import SnapKit
import Reusable

class GLPrebuiltLiveStreamingVC: ZegoUIKitPrebuiltLiveStreamingVC {
    /// 展会id
    var exhibitionId: Int?
    /// 主播Id
    var hostId: String?
    // 店铺id
    var shopId: Int?
    
    /// 直播间数据模型
    var liveRoomModel: GLLiveStreamingConfigModel? {
        didSet {
            self.shopId = liveRoomModel?.shopId
            if let headIconView = self.headIconView as? GLLiveHostHeaderView {
                headIconView.avatarIV.kf.setImage(with: URL(string: liveRoomModel?.avatar ?? ""))
                
                let name = LanguageManager.currentLanguageToText(liveRoomModel?.userName, liveRoomModel?.userNameRu)
                
                headIconView.headNameLabel.text = name //LanguageManager.currentLanguageToText(liveRoomModel?.userName, liveRoomModel?.userNameRu)
                
                headIconView.starView.rating = Double(liveRoomModel?.rating ?? "0") ?? 0
                if let country = liveRoomModel?.country {
                    headIconView.nationalFlagIV.isHidden = false
                    headIconView.nationalFlagIV.image = UIImage(named: AreaCodeModel.country(country).image)
                } else {
                    headIconView.nationalFlagIV.isHidden = true
                }
                //                headIconView.layoutIfNeeded()
            }
        }
    }
    
    lazy var gl_bottomBar: GLLiveStreamBottomBar = {
        let bar = GLLiveStreamBottomBar()
        bar.userID = userID
        bar.config = self.config
        bar.delegate = self.help as! GLPrebuiltLiveStreamingVC_Help
        bar.liveStatus = self.liveStatus
        return bar
    }()
    
    // WKWebView
    lazy var shoppingCarWebView: WKWebView = {
        let webVC = BaseWebViewController(url: "", displaysWebViewTitle: false, isNavBarHide: true)
        
        self.addChild(webVC)
        webVC.wkWebView.frame = CGRect(x: 0, y: 0, width: xScreenW, height: xScreenH * 2 / 3)
        return webVC.wkWebView
    }()
    
    
    
    override func createHelp() -> ZegoUIKitPrebuiltLiveStreamingVC_Help {
        return GLPrebuiltLiveStreamingVC_Help()
    }
    
    override func viewDidLoad() {
        self.bottomBar = self.gl_bottomBar
        self.headIconView = GLLiveHostHeaderView()
        
        super.viewDidLoad()
        
        // MARK: 正确逻辑
        //        if config.role != .host {
        // 拉取直播间信息
        fetchLiveRoomData()
        //        }
    }
    open override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        IQKeyboardManager.shared.isEnabled = false
        self.navigationController?.navigationBar.isHidden = true
        UIApplication.sg.isIdleTimerDisabled(true)
    }
    
    open override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        IQKeyboardManager.shared.isEnabled = true
        self.navigationController?.navigationBar.isHidden = false
    }
    
    open override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        UIApplication.sg.isIdleTimerDisabled(false)
    }
    
    
    override func setupUI() {
        createAudioVideoViewContainer()
        self.view.backgroundColor = UIColor.white
        self.view.addSubview(self.backgroundView)
        self.view.addSubview(self.switchCameraButton)
        self.view.addSubview(self.headIconView)
        self.view.addSubview(self.leaveButton)
        self.view.addSubview(self.memberButton)
        self.view.addSubview(self.hostThreeView)
        self.view.addSubview(self.redDot)
        // self.view.addSubview(self.messageView)
        self.view.addSubview(self.bottomBar)
        // self.view.addSubview(self.inputTextView)
        self.view.addSubview(self.backButton)
        // self.view.addSubview(self.applyConnectView)
        
        view.addSubview(messageView)
        messageView.snp.makeConstraints { make in
            make.left.equalTo(headIconView.snp.left)
            make.bottom.equalTo(bottomBar.snp.top)
            make.width.equalTo(xScreenW*2/3)
            make.height.equalTo(200)
        }
        
        view.addSubview(translationView)
        translationView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()//equalTo(headIconView.snp.left)
            make.top.equalTo(headIconView.snp.bottom).offset(16)
            make.height.lessThanOrEqualTo(xScreenH*0.5)
        }
        
        self.createNormalStartLiveButton()
        if let startLiveButton = startLiveButton {
            self.view.bringSubviewToFront(startLiveButton)
        }
        if let pkBattleView = pkBattleView {
            self.view.insertSubview(pkBattleView, at: 0)
        }
        self.memberButton.currentHost = self.currentHost
        self.setupLayout()
        self.setUIDisplayStatus()
    }
    
    override func setupLayout() {
        self.audioVideoContainer?.view.frame = CGRect(x: 0, y: 0, width: self.view.bounds.size.width, height: self.view.bounds.size.height)
        self.backgroundView.frame = CGRect(x: 0, y: 0, width: self.view.bounds.size.width, height: self.view.bounds.size.height)
        self.headIconView.frame = CGRect(x: 16, y: 53, width: 150, height: 60)
        self.backButton.frame = CGRect(x: 4, y: 50, width: 40, height: 40)
        self.pkBattleView?.frame = CGRect(x: 0, y: 0, width: view.bounds.size.width, height: view.bounds.size.height)
        self.switchCameraButton.frame = CGRect(x: self.view.frame.size.width - 52, y: 52, width: 36, height: 36)
        self.leaveButton.frame = CGRect(x: self.view.frame.size.width - 40, y: 57, width: 30, height: 30)
        //        self.leaveButton.backgroundColor = UIColor.colorWithHexString("#1E2740", alpha: 0.4)
        //        self.leaveButton.layer.masksToBounds = true
        //        self.leaveButton.layer.cornerRadius = 13
        self.memberButton.frame = CGRect(x: self.view.frame.size.width - 40 - 35, y: 56, width: 30, height: 30)
        self.memberButton.layer.masksToBounds = true
        self.memberButton.layer.cornerRadius = 15
        self.memberButton.backgroundColor = UIColor.colorWithHexString("#000000", alpha: 0.3)
        self.hostThreeView.frame = CGRect(x: self.headIconView.frame.maxX + 10, y: 56, width: 100, height: 30)
        self.redDot.frame = CGRect(x: self.memberButton.frame.maxX - 8, y: self.memberButton.frame.minY, width: 8, height: 8)
        self.redDot.layer.masksToBounds = true
        self.redDot.layer.cornerRadius = 4
        self.bottomBar.frame = CGRect(x: 0, y: self.view.frame.size.height - 72, width: self.view.frame.size.width, height: 62)
        // self.messageView.frame = CGRect(x: 16, y: self.view.frame.size.height - 72 - 200, width: UIkitLiveScreenWidth - 16 - 117, height: 200)
        self.startLiveButton?.frame = CGRect(x: (self.view.frame.size.width - 150) / 2, y: self.view.frame.size.height - 44 - 48.5, width: 150, height: 44)
        //        self.applyConnectView.frame = CGRect(x: self.view.frame.size.width - 100, y: 340, width: 90, height: 290)
    }
    
    
    init(_ appID: UInt32, appSign: String, userID: String, userName: String, liveID: String, config: ZegoUIKitPrebuiltLiveStreamingConfig, hostId: String, exhibitionId: Int) {
        
        super.init(appID, appSign: appSign, userID: userID, userName: userName, liveID: liveID, config: config)
        self.hostId = hostId
        self.exhibitionId = exhibitionId
    }
    
    @MainActor required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func getShopId() -> Int? {
        if  let shopId = self.shopId {
            return shopId
        } else {
            YLHUD.showMessage("当前直播间没有店铺".localized(.live))
            return nil
        }
    }
    
    // 购物车
    func showCarWebview() {
        guard let shopId = self.getShopId(), let url = URL(string: H5UrlManager.shoppingCarUrl(bId: String(shopId))) else { return }
        
        self.shoppingCarWebView.load(URLRequest(url: url))
        JFPopupView.popup.bottomSheet(yourView: self.view) { mainContainer in
            self.shoppingCarWebView
        }
    }
    
    // 店铺详情
    func pushShop() {
        guard let userID = hostId else { return }
        guard let shopId = self.getShopId() else { return  }
        YLHUD.showLottie()
        MineMainViewModel.loadUserInfo(userID) { [weak self] userModel in
            YLHUD.hideHUD()
            if userModel?.identityType == .supplier {
                self?.push(BaseWebViewController(url: H5UrlManager.storeUrl(storeId: String(shopId)) , isNavBarHide: true))
                
            } else {
                self?.push(BaseWebViewController(url: H5UrlManager.personalHomepage(userID) , isNavBarHide: true))
            }
        }
    }
}

//extension GLPrebuiltLiveStreamingVC: WKScriptMessageHandler {
//    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
//        xLog("message.name: \(message.name)")
//
//        if message.name != "NativeBridge" {
//            return
//        }
//
//        xLog("JS传递的参数: \(message.body)")
//
//
//    }
//}

// MARK:
class GLPrebuiltLiveStreamingVC_Help: ZegoUIKitPrebuiltLiveStreamingVC_Help, GLLiveStreamBottomBarDelegate {
    
    // 为了减少对源码的修改, 隐藏源码中的显示的多余元素
    override func getForegroundView(_ userInfo: ZegoUIKitUser?) -> ZegoBaseAudioVideoForegroundView? {
//        if let userInfo = userInfo, let userId = userInfo.userID {
//            if let userModel = UserModel.fetchUser(userId.sg.toInt) {
//                if userModel.identityType == .interpreter {
//                    // 是翻译
//                    let foregroundView = ZegoBaseAudioVideoForegroundView(frame: .zero, userID: nil, delegate: nil)
//                    let nicknameLabel = UILabel()
//                    nicknameLabel.text = "翻译".localized(.login)
//                    nicknameLabel.font = .systemFont(ofSize: 10)
//                    nicknameLabel.textColor = .white
//                    foregroundView.addSubview(nicknameLabel)
//                    nicknameLabel.snp.makeConstraints { make in
//                        make.top.equalToSuperview().offset(4)
//                        make.left.equalToSuperview().offset(4)
//                    }
//                }
//            }
//        }
        return ZegoBaseAudioVideoForegroundView(frame: .zero, userID: nil, delegate: nil)
    }
    
    /// 点击聊天消息按钮
    func gl_onInRoomMessageButtonClick() {
        self.onInRoomMessageButtonClick()
    }
    
    func gl_onInRoomShareButtonClick() {
        xLog("分享直播间链接")
        guard let gl_liveStreamVC = self.liveStreamingVC as? GLPrebuiltLiveStreamingVC else { return }

        let shareView = GLLiveShareView.loadFromNib()
        shareView.closeHandler = {
            gl_liveStreamVC.popup.dismissPopup()
        }
        shareView.shareHandler = {
            xLog("直播间 id: \(gl_liveStreamVC.liveID ?? "")")
            let board = UIPasteboard.general
            board.string = "http://gluzlive.com?roomId=\(gl_liveStreamVC.liveID ?? "")&exhibitionId=\(String(gl_liveStreamVC.exhibitionId!))&hostId=\(gl_liveStreamVC.hostId ?? "")"
            YLHUD.showMessage("复制到剪切板".localized(.tran))
        }
        
        gl_liveStreamVC.popup.bottomSheet {
            shareView
        }
        
    }
    
    //    /// 摄像头开关点击
    //    func gl_onToggleCameraButtonClick(_ isOn: Bool) {
    //
    //    }
    //    /// 麦克风
    //    func gl_onToggleMicButtonClick(_ isOn: Bool) {
    //
    //    }
    //    /// 切换摄像头点击
    //    func gl_onGZSwitchCameraButtonClick(_ isFrontFacing: Bool) {
    //
    //    }
    /// 购物车点击
    func gl_shoppingCarButtonClick() {
        guard let gl_liveStreamVC = self.liveStreamingVC as? GLPrebuiltLiveStreamingVC else { return }
        gl_liveStreamVC.showCarWebview()
    }
    
    /// 商铺点击
    func gl_shopButtonClick() {
        guard let gl_liveStreamVC = self.liveStreamingVC as? GLPrebuiltLiveStreamingVC else { return }
        gl_liveStreamVC.pushShop()
    }
    /// 1v1点击
    func gl_appointmentButtonClick() {
        
        if let gl_liveVC = self.liveStreamingVC as? GLPrebuiltLiveStreamingVC, let hostId = gl_liveVC.hostId, let hId = Int(hostId) {
            GLLive_Helper.appointment1V1(receiveUserId: hId, roomId: gl_liveVC.liveID)
        }
    }
    
    /// 连麦控制按钮点击事件
    /// - Parameters:
    ///   - type: 按钮类型（请求/取消/结束连麦）
    ///   - sender: 事件源按钮
    func gl_coHostControlButtonDidClick(_ type: CoHostControlButtonType, sender: ZegoCoHostControlButton) {
        self.coHostControlButtonDidClick(type, sender: sender)
    }
}


// MARK: 自定义直播间的相关操作
extension GLPrebuiltLiveStreamingVC {
    
    /// 拉取直播间的配置信息 主播的相关信息设置
    /// role = .host 点击开始时候调用, 传递直播间参数, 如果不点开始应该不算开播, 不应该调用
    /// 其他角色应该是进来就调用
    func fetchLiveRoomData() {
        
        if let exhibitionId = self.exhibitionId, let hostId = self.hostId, let roomId = self.liveID {
            let target = LiveAPI.startLive(exhibitionId: exhibitionId, userId: hostId, roomId: roomId)
            
            YLHUD.showLottie()
            YLRequest.request(target) { result in
                switch result {
                case .success(let res):
                    YLHUD.hideHUD()
                    if let liveHomeModel = JsonUtil.modelFromDictionary(res.dataDictionary, GLLiveStreamingConfigModel.self) {
                        
                        self.liveRoomModel = liveHomeModel
                        
                    }
                case .failure(let err):
                    YLHUD.showHint(.error, err.errMsg)
                }
            }
            
        } else {
            YLHUD.showMessage("暂无展会")
        }
        
    }
    
}
